/**
 * @author kobe
 * @date   16/06/30
 */

import FooterBtn from '../components/detail/FooterBtn';
import BottomForm from '../components/detail/BottomForm';
import TextArea from '../components/form/TextArea';
import Swiper from "../components/Swiper";
import LargeImg from "../components/LargeImg";

var lf = liefeng,
	RC = React.createClass,
	ajax = lf.utils.ajax,
	getUrlParam = lf.utils.getUrlParam,
	taskId = getUrlParam('taskId'), //本页面基本所有ajax都需要用到
	status = getUrlParam('status'), //同上
	doClose = lf.bridgeJs.doClose,
	fmt = 'yyyy-MM-dd hh:mm',
	translateTime = lf.utils.format;

const TYPE = getUrlParam('type'),
	  CONFIRM = 'confirm',
	  FEEDBACK = 'feedback',
	  CHECK = 'check',
	  BACK = 'back',
	  HELP = 'help',
	  COMPLETE = 'complete',
	  DISPATCH = 'dispatch',
	  DELETE = 'delete'

var Line = RC({

	render(){

		var me = this,
			key = 0;

		var data = this.props.data,
			checkFile = true,
			content = '';

		if(data.type == 'imgs' && !data.imgUrl == ''){

			var imgUrl = data.imgUrl.split(",");

			checkFile = false;

			content = imgUrl.map(function (url) {
				var suffix = url.substring(url.lastIndexOf('.') + 1),
					isImg = false,
					checkFile = ['jpeg','gif','jpg','png','bmp','pic'];

				for(var i = 0;i<checkFile.length;i++){
					if(suffix == checkFile[i]){
						isImg = true;
						break;
					}
				}

				if(isImg){
					key++;
					return(
						<SetImg imgSrc={url} key={key} showLargeImg={me.props.showLargeImg}/>
					)
				}else{
					return(
						false
					)
				}
			})

			for(let i=0;i<content.length;i++){
				if(!(content[i] == false)){
					checkFile = true;
					break;
				};
			}
		}
		else{
			content = data.content
		}

		if(!content=="" && checkFile){
			return(
				<div className={"line " + data.display}>
					<div className="line-title">{data.title}</div>
					<div className="line-content">{content}</div>
				</div>
			)
		}else{
			return(
				<div className="ele-hide"></div>  //当那条没信息就隐藏
			)
		}


	}
})


var SetImg = RC({
	componentDidMount() {
		var showLargeImg = this.props.showLargeImg;

		$('.toLarge').on('tap',function () {
			var url = $(this).attr('src');

			showLargeImg(url);
		})

	},
	render(){
		var url = this.props.imgSrc;
		return(
			<div className="imgs">
				<img src={url} className="toLarge"/>
			</div>
		)
	}
})

var SetLine = RC({
	getInitialState(){
		return({largeSrc:''})
	},
	showLargeImg(url){
		this.setState({
			largeSrc:url
		})
	},
	render(){
		var me = this,
			data = this.props.data;

		var statue = '';


		//优化
		if(data.nodeCode == '02'){
			statue = '确认';
		}else if(data.nodeCode == '03'){
			statue = '反馈';
		}else if(data.nodeCode == '04'){
			statue = '审核';
		}

		if(data.taskHandleVoList){
			data = [
				{title: '派遣人',content:data.creatorName},
				{title: '开始时间',content:translateTime(data.createTime,fmt)},
				{title: '截止时间',content:translateTime(data.endTime,fmt)},
				{title: '任务描述',content:data.content},
				{title: '图片',type:'imgs',imgUrl:data.imgUrl}
			]
		}else if(data.nodeCode == '02'){
			data = [
				{title: '确认人', content: data.staffName},
				{title: '确认时间', content:translateTime(data.createTime,fmt)},
				{title: '执行计划', content:data.content},
			]
		}else if(data.nodeCode == '03'){
			data = [
				{title: '执行人', content:data.staffName},
				{title: '处理时间', content:translateTime(data.createTime,fmt)},
				{title: '处理结果', content:data.content},
				{title: '图片',type:'imgs',imgUrl:data.imgUrl}
			]
		}else if(data.nodeCode == '04'){
			data = [
				{title: '审核人', content: data.staffName},
				{title: '审核时间', content:translateTime(data.createTime,fmt)},
				{title: '审核结果', content:data.statusReview == 1 ? '通过' : '不通过'},
				{title: '驳回原因',content:data.content,display: data.statusReview == 1 ? 'ele-hide' : ''}
			]
		}

		var set_line = data.map(function (data) {
			return(
				<Line data={data} showLargeImg={me.showLargeImg}/>
			)
		})

		return(
			<div className="mission-group">
				<div className="statue">{statue}</div>
				{set_line}
				<LargeImg src={this.state.largeSrc}/>
			</div>
		)


	}
})

var MissionContent = RC({
	render(){

		var data = this.props.data,
			setContent = data.taskHandleVoList;

		setContent.unshift(data);

		console.log(setContent)

		var line = setContent.map(function (data) {
			return(
				<div className="group">
					<SetLine data={data} />
				</div>
			)
		})

		return(
			<div className="mission-content">
				{line}
				<InputInfo />
			</div>
		)
			// <MissionInfo data={data}/>
	}
});

var InputInfo = RC({
	getInitialState() {
		return {
			largeImgSrc: '',
			imgList: [],
		}
	},
	componentDidMount() {
		//时间紧急 先拷daily-work-add的代码 日后研究 TODO
		React.findDOMNode(this.refs.upLoadBtn).addEventListener('tap', () => {
			lf.appJs.selectPhoto(9);
		});

		lf.appJs.registerHandler('getPhotoFromApp', (data) => {

			var imgList = this.state.imgList;

			data.indexOf(',') != -1 && data.split(',').map( function ( item ) {
				imgList.unshift(item);
			});

			data.indexOf(',') == -1 && imgList.unshift(data);

			if (imgList.length > 9) {
				alert('最多只能上传9张图片!');
				return;
			}
			this.setState({imgList: imgList});
		});
	},
	deleteImg(e) {
		let $node = $(e.target),
			$img = $node.siblings('img'),
			imgList = this.state.imgList;

		for(let i = 0; i < imgList.length; i++) {
			let img = imgList[i];
			if(img == $img.attr('src')) {
				imgList.splice(i,1);
				break;
			}
		}

		this.setState({
			imgList: imgList
		});
	},
	enlargeHandler(src) {
		this.setState({largeImgSrc: src});
	},
	render(){
		var isHide = 'ele-hide',
			textAreaTitle='',
			placeHolder = '',
			addImg = 'ele-hide';

		if(TYPE == CONFIRM){
			isHide = '';
			textAreaTitle = '执行计划';
			placeHolder = '说说你的措施或计划(必填),限200字';
		}else if(TYPE == FEEDBACK){
			isHide = '';
			addImg = '';
			textAreaTitle = '反馈详情';
			placeHolder = '处理结果(必填),限200字';
		}

		return(
			<div className={"bottom-info " + isHide} >
				<div className="line">
					<div className="line-title">{textAreaTitle}</div>
					<TextArea addClass="manage input-text" name="planText" placeholder={placeHolder} />
				</div>
				<div className={"line " + addImg}>
					<div className="bottom-form-handle-img">
						<a className="up-load-img-btn" ref="upLoadBtn" href="javascript:">上传图片</a>
						<Swiper imgList={this.state.imgList}
								deleteFn={this.deleteImg}
								enlargeHandler={this.enlargeHandler}
								floatFlag={false} />
					</div>
				</div>
				<LargeImg src={this.state.largeImgSrc}/>
			</div>
		)
	}
})

var Footer = RC({
	getInitialState(){
		return({
			formVisible: '',
			formConVisible: '',
			clickStatue: true,
		})
	},
	determine(){

		if(!this.state.clickStatue){
			return;
		}

		var me = this,
			content = $('#planText').val();

		if(!content){
			if(TYPE == CONFIRM){
				alert('请填写执行计划');
			}else if(TYPE == FEEDBACK){
				alert('请填写反馈详情')
			}

			return;
		}else if(content.length > 200){
			alert('填写不能超过200字');
			return;
		}

		if(TYPE == CONFIRM){

			var data = {
				taskId: taskId,
				status: status,
				staffId: me.props.user.id,
				content: content
			}

			me.updateTask(data);
		}else if(TYPE == FEEDBACK){
			var pic = $('.swiper-activity-img > img'),
				pics = [];

			for(var i = 0;i<pic.length;i++){
				pics[i] = pic.eq(i).attr('src');
			}

			var createFeedback = function (url) {

				var pics = url.split(","),
					imgMessage = '';

				for(var i = 0;i<pics.length;i++){
					imgMessage = imgMessage + pics[i] + ',,|'
				}

				var data = {
					taskId: taskId,
					status: status,
					staffId: me.props.user.id,
					content: content,
					imgMessage: imgMessage,
				}

				me.updateTask(data);

				this.setState({clickStatue:true});
			};

			if(pic.length == 0){

				var data = {
					taskId: taskId,
					status: status,
					staffId: me.props.user.id,
					content: content,
				}

				me.updateTask(data);

			}else{
				this.setState({clickStatue:false});
				lf.bridgeJs.uploadImg(pics.toString(),createFeedback);
			}

		}
	},
	reject(){
		this.setState({
			formVisible: 'this',
			formConVisible: 'this',
		});
	},
	pass(){
		var data = {
			taskId: taskId,
			status: status,
			staffId: this.props.user.id,
			content: "通过",  //按照徐大大的接口要求 通过的必须传个通过过去
			statusReview: 1,
		}
		this.updateTask(data);
	},
	withdraw(){
		
	},
	feedbackConfirm(){
		var  content = $('#result').val();

		if(!content){
			alert('请填写驳回原因');
			return;
		}else if(content.length > 200){
			alert('填写不能超过200字');
			return;
		}

		var data = {
			taskId: taskId,
			status: status,
			staffId: this.props.user.id,
			statusReview: 2,
			content: content
		}
		this.updateTask(data);
	},
	itemRender(){
		return (
			<div className="bottom-form">
				<textarea placeholder="驳回原因(必填)" name="result" id="result"></textarea>
			</div>
		)
	},
	hideBottomForm() {
		this.setState({
			formVisible: '',
			formConVisible: '',
		});
	},
	cancel(){
		var me = this;
		var data = {
			'content': '您要删除任务吗?',
		}
		lf.appJs.confirm(data,me.deletedFn);

	},
	deletedFn(){
		ajax({
			type: "POST",
			data:{
				taskId: taskId,
			},
			success: function(data) {
				//成功
				if ( data.code == '200' ) {
					// debugAlert('先测试 success');
					alert('操作成功!', () => doClose());
				}
				else{
					alert(data.desc,() => doClose());
				}
			}
		},lf.api.worktable.deleteTask);
	},
	like(){

	},
	updateTask(data){
		ajax({
			type: "POST",
			data: data,
			success: function(data) {
				//成功
				if ( data.code == '200' ) {
					// debugAlert('先测试 success');
					// mui.toast('操作成功');
					alert('操作成功!', () => doClose());
				}
				else{
					alert(data.desc,() => doClose());
				}
			}
		},lf.api.worktable.updateTask);


	},
	render(){

		var btn = [],
			hide = ''; //当底部没有按钮的时候,隐藏

		var determine = {aLinkClass: 'green', clickHandler: this.determine, text: '确定'},
			reject = {aLinkClass: 'green', clickHandler: this.reject, text: '驳回'},
			pass = {aLinkClass: 'green', clickHandler: this.pass, text: '通过'},
			back = {aLinkClass: 'green', clickHandler: this.withdraw, text: '撤回'},
			cancel = {aLinkClass: 'green', clickHandler: this.cancel, text: '删除'},
			like= {aLinkClass: 'green', clickHandler: this.like, text: '收藏'};

		var formFooterBtn = [
			{aLinkClass: 'green ', clickHandler:  this.hideBottomForm, text: '取消'},
			{aLinkClass: 'green', clickHandler: this.feedbackConfirm, text: '确定'},
		];

		if(TYPE==CONFIRM || TYPE == FEEDBACK){
			btn.push(determine);
		}else if(TYPE == CHECK){
			btn.push(reject,pass);
		}else if(TYPE == BACK){
			btn.push(back);
		}else if(TYPE == HELP){
			btn.push();
		}else if(TYPE == DELETE){
			btn.push(cancel);
		}else if(TYPE == DISPATCH){
			hide = 'ele-hide';
		}
		else if(TYPE == COMPLETE){
			// btn.push(like);  //TODO 还没接口 先隐藏收藏按钮
			hide = 'ele-hide';
		}

		return(
			<div className={"footer " + hide}>
				<FooterBtn data={btn} />
				<BottomForm
					itemRender={this.itemRender}
					formFooterBtn={formFooterBtn}
					formVisible={this.state.formVisible}
					formConVisible={this.state.formConVisible}
				/>
			</div>
		)
	}
})

var Container = RC({
	getInitialState(){
		return({
			data:{
				taskHandleVoList:[]
			}
		})
	},
	componentWillMount() {
		var me = this;
		ajax({
			type: "GET",
			data:{
				staffId: me.props.user.id,
				taskId: taskId
			},
			success: function(data) {
				//成功
				if ( data.code == '200' ) {
					var data = data.data;
					me.setState({
						data: data
					});
				}
				else{
					alert(data.desc);
				}
			}
		},lf.api.worktable.getTask);
	},
	render(){
		var user = this.props.user;

		return(
			<div className="daily-work-detail">
				<MissionContent user={user} data={this.state.data}/>
				<Footer user={user} />
			</div>
		)
	}
})

lf.bridgeJs.getUser(function (user) {
	React.render(
		<Container user={user} />,
		document.getElementById('root'), function () {
			$('#root').css('background', 'none');
		}
	)
})



